package com.coastwe.dahua.chapter03;

public class LinkListNoHeadDaHua {
    private int size;
    private Node head;

    public LinkListNoHeadDaHua() {
        this.size = 0;
        this.head = null;
    }

    public boolean listInsert(int index, int value) {
        if (index < 0 || index > size) {
            return false;
        }
        Node temp = head;
        Node p = createNode(value);
        if (index == 0) {
            if (head == null) {
                head = p;
            } else {
                p.next = head;
                head = p;
            }
        } else {
            temp = head;
            for (int i = 0; i < index - 1; i++) {
                temp = temp.next;
            }
            p.next = temp.next;
            temp.next = p;
        }
        size++;
        return true;
    }

    public boolean listDel(int index) {
        if (index < 0 || index >= size) {
            return false;
        }
        if (index == 0) {
            head = head.next;
        } else {
            Node p = head;
            for (int i = 0; i < index - 1; i++) {
                p = p.next;
            }
            p.next = p.next.next;
        }
        size--;
        return true;
    }

    public void printAll() {
        Node temp = head;
        for (int i = 0; i < size; i++) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    public void listTraverse() {
        if (head == null) {
            return;
        } else {
            Node temp = traverse(head);
            temp.next = null;
        }
    }

    private Node traverse(Node node) {
        if (node.next == null) {
            head = node;
            return node;
        }
        Node pre = traverse(node.next);
        pre.next = node;
        return node;
    }

    public static void main(String[] args) {
        LinkListNoHeadDaHua list = new LinkListNoHeadDaHua();
        list.listInsert(0, 1);
        list.listInsert(1, 2);
        list.listInsert(2, 3);
        list.listInsert(3, 4);
        list.listInsert(4, 5);
        list.listInsert(5, 6);
        list.printAll();
        list.listInsert(0, 7);
        list.listInsert(3, 7);
        list.listInsert(8, 7);
        list.listInsert(8, 7);
        list.printAll();
        System.out.println("del");
        list.listDel(0);
        list.printAll();
        list.listDel(2);
        list.printAll();
        list.listDel(7);
        list.printAll();
        list.listTraverse();
        list.printAll();

    }

    private static Node createNode(int value) {
        return new Node(value, null);
    }

    private static class Node {
        int data;
        Node next;

        Node(int value, Node next) {
            this.data = value;
            this.next = next;
        }
    }

}